/**
 * 
 */
package com.hst.web.auth.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hst.core.auth.IUser;
import com.hst.core.auth.IUserAuth;
import com.hst.core.dao.IORDao;
import com.hst.core.dao.ISQLDao;
import com.hst.core.dao.ORQuery;
import com.hst.core.dao.ORQuery.Op;
import com.hst.web.auth.po.User;
import com.hst.web.sys.entity.TUser;
import com.hst.web.sys.entity.TUserSession;

/**
 * @author wangyh
 *
 */
@Service
public class UserAuthService implements IUserAuth {
	@Autowired
	IORDao dao;

	@Autowired
	ISQLDao sql;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.hst.core.auth.IUserAuth#getUser(java.lang.String)
	 */
	@Override
	public IUser getUser(String sso) {
		User u = null;
		List<TUserSession> tus = dao.list(TUserSession.class, new ORQuery(Op.eq, "id", sso));
		if (tus.size() == 1) {
			TUser user = dao.get(TUser.class, tus.get(0).getUserid());
			if (null != user) {
				u = new User(sso,tus.get(0).getCompanyCode(),"", user);
				u.setPrivileges(getUserPrivileges(u.getId()));
			}
		}

		return u;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.hst.core.auth.IUserAuth#getUser(java.lang.String, java.lang.String)
	 */
	@Override
	public IUser getUser(String userid, String passwd) {
		User u = null;
		List<TUser> tus = dao.list(TUser.class, new ORQuery(Op.eq, "operatorNbr", userid));
		if (tus.size() == 1) {
			TUser tu = tus.get(0);
			if (tu.getPassword().equals(passwd) && "1".equals(tu.getValidflag())) {
				u = new User("","","", tu);
				u.setPrivileges(getUserPrivileges(u.getId()));
			}
		}

		return u;
	}

	/**
	 * 获取用户权限
	 * 
	 * @param userid
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<String> getUserPrivileges(String userid) {
		Map<String, Object> params = new HashMap<>();
		params.put("userid", userid);
		return (List<String>) sql.query("session.privileges", params);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.hst.core.auth.IUserAuth#hasAuth(com.hst.core.auth.IUser,
	 * java.lang.String)
	 */
	@Override
	public boolean hasAuth(IUser user, String authId) {
		User u = (User) user;
		List<String> privileges = u.getPrivileges();
		if (null == privileges) {
			privileges = getUserPrivileges(u.getId());
			u.setPrivileges(privileges);
		}

		return privileges.contains(authId);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.hst.core.auth.IUserAuth#toAuthFault(javax.servlet.http.
	 * HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.String)
	 */
	@Override
	public void toAuthFault(HttpServletRequest request, HttpServletResponse response, String reason) throws Exception {
//		response.setHeader("WWW-Authenticate", "Basic realm=\"UNAUTHORIZED\"");
//		response.setStatus(HttpStatus.UNAUTHORIZED.value());
	}
}
